<template>
  <view class="page-wrapper address-page page">
    <div class="page-title">收件人信息 Recipient Information</div>
    <div class="ul wrap">
      <div class="li" v-for="(item, index) in list" :key="item.id">
        <div class="top" @click="setAddress(item)">
          <div class="tl">{{ item.name }} {{ item.phone }}</div>
          <div class="tl">
            {{ item.province + item.city + item.district + item.street + item.placeInfo }}
          </div>
        </div>
        <div class="bottom">
          <div class="left" @click="toSetDefault(item)">
            {{ item.isDefault == 1 ? '已设为默认地址' : '设为默认地址' }}
          </div>
          <div class="right">
            <div class="btn" @click="toEdit(item.id)">修改</div>
            <div class="btn" @click="deleteBtn(item.id)">删除</div>
          </div>
        </div>
      </div>
    </div>
    <div class="wrap">
      <div class="add-new-btn">
        <div class="btn" @click="toAddNewAddress">添加新地址</div>
      </div>
    </div>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, watch, computed } from 'vue'
import { addressList, setDefaultAddress, deleteAddress } from '@/utils/api/address'

import { onLoad, onShow } from '@dcloudio/uni-app'

let prevPage: string = ''
let list = ref<any>([])
const getAddressList = async () => {
  let res = await addressList({})
  console.log('res', res)
  if (res.code == 200 && Array.isArray(res.data.list)) {
    list.value = res.data.list
  } else {
    console.warn('地址列表返回数据格式异常:', res)
  }
}
const toAddNewAddress = () => {
  uni.navigateTo({
    url: '/pages/addAddress/addAddress'
  })
}

const toSetDefault = async (item: any) => {
  if (item.isDefault != 1) {
    const res = await setDefaultAddress({ id: item.id })
    if (res.code == 200) {
      getAddressList()
    }
  }
}

const setAddress = (item: any) => {
  if (prevPage === 'pages/purchaseConfirm/purchaseConfirm') {
    uni.setStorageSync('checkedAddress', item)
    uni.navigateBack()
  }
}

const toEdit = (id: string | number) => {
  uni.navigateTo({
    url: '/pages/addAddress/addAddress?id=' + id
  })
}
const deleteBtn = (id: string | number) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该地址吗？',
    success: async (res) => {
      if (res.confirm) {
        const res = await deleteAddress({ id: id })
        if (res.code == 200) {
          getAddressList()
        }
      }
    }
  })
}

onMounted(() => {
  let pages = getCurrentPages()
  let prevPageVm = pages[pages.length - 2]
  prevPage = prevPageVm.route
})
onShow(() => {
  getAddressList()
})
</script>

<style lang="scss" scoped>
@import './address.scss';
</style>
